package com.example.service.other;

import com.example.entity.Result;
import com.example.entity.SeckillMessage;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import static com.example.entity.constant.mq.RabbitmqConstant.SECKILL_EXCHANGE;
import static com.example.entity.constant.mq.RabbitmqConstant.SECKILL_ROUTING_KEY;
import static com.example.entity.constant.redis.SeckillConstant.RESULT_KEY_PREFIX;
import static com.example.entity.constant.redis.SeckillConstant.USER_KEY_PREFIX;

@Service
public class SeckillCoreService {

    @Autowired
    private TokenService tokenService;

    @Autowired
    private UserSeckillValidator userValidator;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private StringRedisTemplate redisTemplate;


    /**
     * 处理秒杀请求
     * @param userId 用户ID
     * @param goodsId 商品ID
     * @return 包含令牌的响应结果
     */
    public Result<String> doSeckill(Long userId, Long goodsId) {
        // 1. 用户校验：是否已参与
        String userKey = USER_KEY_PREFIX + goodsId;
        if (!userValidator.checkUser(userId, goodsId)) {
            return Result.fail("您已参与过秒杀，请等待结果");
        }

        // 2. 获取令牌：无令牌则表示已抢完
        String token = tokenService.acquireToken(goodsId);
        if (token == null) {
            // 清除用户记录，允许再次尝试
            redisTemplate.opsForSet().remove(userKey, userId.toString());
            return Result.fail("商品已抢完");
        }

        // 3. 标记令牌为"处理中"
        String resultKey = RESULT_KEY_PREFIX + token;
        redisTemplate.opsForValue().set(resultKey, "PROCESSING", 30, java.util.concurrent.TimeUnit.SECONDS);

        // 4. 发送消息到队列，异步处理
        SeckillMessage message = new SeckillMessage(userId, goodsId, token);
        rabbitTemplate.convertAndSend(SECKILL_EXCHANGE, SECKILL_ROUTING_KEY, message);

        // 5. 返回令牌，前端凭此建立SSE连接
        return Result.success(token);
    }
}

